define([
	'jquery',
	'underscore',
	'backbone',
	'baseView',
	'text!o2o/role/detail.html',
	'js/myUtil.js'
], function($, _, Backbone, BaseView, tpl, myUtil) {
	return BaseView.extend({
		render: function(cb) {
			var that = this;
			var roleId = this.options.roleId;
			myUtil.getRole(roleId, function(err, res) {
				if (that.showError(err, res)) return;

				var roleHavePermit = res.result.role.permissions;
				var allPermit = res.result.permissions;
				allPermit.forEach(function(item) {
					if (roleHavePermit.indexOf(item.code) >= 0) {
						item.have = 1;
					}
				});

				var tmpl = _.template(tpl);
				var tmpl2 = tmpl({
					item: res.result
				});
				$(that.el).html(tmpl2);
				$(that.el).find('.switchEditable').attr('disabled', true);
				if (!$(this.el).is(":visible")) // if hide then show
					that.show();
				cb && cb();
			});
		},

		events: {
			"click #enableEditRole": "enableEditRole",
			"click #commitEditRole": "commitEditRole",
		},

		enableEditRole: function(event) {
			event.preventDefault();
			var target = $('.switchEditable');
			var isDisabled = target.attr('disabled');

			if (isDisabled) {
				console.log('disable -> enable');
				target.removeAttr('disabled');
				$('#enableEditRole').text('cancle');
			} else {
				blueInk.refreshTop(this.options);
			}
		},

		commitEditRole: function(event) {
			event.preventDefault();
			var formData = $('form#editRole').serializeObject();
			console.log(formData);
			var that = this;
			myUtil.editRole(formData, function(err, res) {
				if (that.showError(err, res)) return;
				console.log(res.result);
				window.location.href = "#o2o/role";
			});
		},

		showError: function(err, res) {
			var nodeTip = $(this.el).find('.tip');
			nodeTip.hide();
			if (err) return nodeTip.text(err).show();
			if (res.errCode !== 0) return nodeTip.text(res.errMsg).show();
			return false; // no error
		}
	});
});